package com.fbt.transfer.app.driver.http;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import cn.hutool.core.text.CharSequenceUtil;
import com.fbt.transfer.app.driver.activity.LoginActivity;
import com.fbt.transfer.app.driver.model.Result;
import com.fbt.transfer.app.driver.util.LogUtils;
import com.fbt.transfer.app.driver.util.UserManager;
import com.fbt.transfer.app.driver.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author tuocoo
 * @date 2024/8/5/15:50
 */
public abstract class AbstractCallback<T> implements Callback<Result<T>> {

  public static final String TAG = "HttpCallback";
  private final Context context;
  private final boolean showError;
  static Map<String, String> authorizationMap = new HashMap<>();
  static List<String> toLoginPageCode = new ArrayList<>();
  static List<String> noPermissionCode = new ArrayList<>();

  static {
    authorizationMap.put("S0401", "用户名或者密码错误");
    authorizationMap.put("S0402", "登录凭据已过期,请重新登录");
    authorizationMap.put("S0403", "您的账号在其它地方登录已被顶下线，请注意账号安全");
    authorizationMap.put("S0404", "账号已被踢下线");
    authorizationMap.put("S0405", "账号已被冻结，请联系客服");
    authorizationMap.put("S0406", "登录凭据格式错误,请重新登录");
    authorizationMap.put("S0407", "请登录后访问");
    authorizationMap.put("S0410", "登录次数超过限制");
    authorizationMap.put("S0411", "您无权限访问该资源，请联系您的上级管理员");
    authorizationMap.put("S0412", "您没有管理该资源,请联系管理员");
    authorizationMap.put("S0413", "token 无效,请重新登录");
    authorizationMap.put("S0418", "登录异常，请联系管理员");
    toLoginPageCode.add("S0402");
    toLoginPageCode.add("S0403");
    toLoginPageCode.add("S0404");
    toLoginPageCode.add("S0406");
    toLoginPageCode.add("S0407");
    toLoginPageCode.add("S0413");
    noPermissionCode.add("S0411");
    noPermissionCode.add("S0412");
  }

  private final Dialog progressDialog;

  protected AbstractCallback (Context context, boolean showProgressDialog, boolean showError) {
    this.context = context;
    if (showProgressDialog) {
      progressDialog = new Dialog(context);
      // 设置加载动画，例如使用进度条对话框
      progressDialog.setContentView(R.layout.loading);
      progressDialog.setCancelable(false);
      progressDialog.show();
    } else {
      progressDialog = null;
    }
    this.showError = showError;
  }

  protected AbstractCallback (Context context, boolean showToast) {
    this.context = context;
    this.showError = showToast;
    progressDialog = null;
  }

  protected AbstractCallback (Context context) {
    this(context, false, false);
  }

  @Override
  public void onResponse (@NotNull Call<Result<T>> call, @NotNull Response<Result<T>> response) {
    if (progressDialog != null && progressDialog.isShowing()) {
      progressDialog.dismiss();
    }
    if (response.isSuccessful()) {
      Result<T> result = response.body();
      if (result != null) {
        if (result.isSuccess()) {
          onSuccess(result.getData());
        } else {
          onFailure(result);
        }
      }
    }
    if (progressDialog != null && progressDialog.isShowing()) {
      progressDialog.dismiss();
    }
  }

  @Override
  public void onFailure (@NotNull Call<Result<T>> call, Throwable t) {
    if (t instanceof java.net.SocketTimeoutException) {
      LogUtils.e(TAG, CharSequenceUtil.format("请求超时,错误信息:{}", t.getMessage()));
      Toast.makeText(context, "网络错误,请稍后重试", Toast.LENGTH_SHORT).show();
    } else {
      LogUtils.e(TAG, CharSequenceUtil.format("请求失败,错误信息:{}", t.getMessage()));
    }
    Optional.ofNullable(progressDialog).ifPresent(Dialog::dismiss);
    if (progressDialog != null && progressDialog.isShowing()) {
      progressDialog.dismiss();
    }
    if (!showError) {
      return;
    }
    onFailure(null);
  }

  /**
   * 请求成功
   *
   * @param data 业务数据
   */
  protected abstract void onSuccess (T data);

  protected void onFailure (Result<T> result) {
    String message;
    if (result == null || (message = result.getMessage()) == null) {
      LogUtils.e(TAG, "请求失败,错误信息:result is null");
      return;
    }
    if (!showError) {
      return;
    }
    LogUtils.e(TAG, CharSequenceUtil.format("请求失败,错误信息:{}", message));
    if (result.getCode().startsWith("S")) {
      // 登陆过期，跳转到登陆页面
      if (!(context instanceof LoginActivity)) {
        UserManager.getInstance(context).clearUserInfo();
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
      }
    }
    // 显示错误信息的逻辑
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }

  ;
}
